import { Injectable, NotFoundException } from '@nestjs/common';
import path from 'path';
import fs from 'fs';
@Injectable()
export class UploadService {

  private fileMap: Record<string, string> = {}
  uploadChunk(file, body) {
    if (!file) throw new NotFoundException('文件不存在')
    return '文件上传成功'
  }

  saveFile(file, body) {
    const { filename, mimetype } = file;
    const fileCategory = this.getFileTypeDir(mimetype)
    const targetDir = path.join(__dirname, '../resource', fileCategory);
    const tempPath = path.join(__dirname, '../resource/temp/single', filename);
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true })
    }
    const targetFile = path.join(targetDir, filename);
    //把文件写入
    fs.renameSync(tempPath, targetFile)
    return `http://192.168.0.109:3000/xiaoluo/${fileCategory}/${filename}`
  }

  checkChunk(body: any) {
    const { fileHash } = body;
    const uploadPath = path.join(__dirname, '../resource/temp/chunked', fileHash);
    //查找分片
    if (!fs.existsSync(uploadPath)) {
      return []
    }
    const files = fs.readdirSync(uploadPath);

    return files.map(f => Number(f.split('-')[0]))
  }

  mergeChunks(body: any) {
    const { filename, fileType, fileHash } = body;
    const fileCategory = this.getFileTypeDir(fileType)
    const uploadPath = path.join(__dirname, '../resource/temp/chunked', fileHash)
    let files = fs.readdirSync(uploadPath);
    // 根据index排序
    files.sort((a: any, b: any) => a.split('-')[0] - b.split('-')[0]);
    const targetDir = path.join(__dirname, '../resource', fileCategory);
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true })
    }
    const targetFile = path.join(targetDir, `${fileHash}-${filename}`);
    files.forEach((item) => {
      fs.appendFileSync(targetFile, fs.readFileSync(path.join(uploadPath, item)))
      fs.unlinkSync(path.join(uploadPath, item))
    })
    //合并完成 删除临时文件夹
    fs.rmdirSync(uploadPath)
    return `http://192.168.0.109:3000/xiaoluo/${fileCategory}/${fileHash}-${filename}`
  }

  getFileTypeDir(mimetype) {
    if (mimetype.startsWith('image/')) return 'images';
    if (mimetype.startsWith('video/')) return 'videos';
    if (mimetype.startsWith('audio/')) return 'audios';
    if (mimetype === 'application/pdf' || mimetype.includes('word') || mimetype.includes('excel') || mimetype.includes('presentation') || mimetype === 'text/plain') return 'docs';
    if (mimetype.includes('zip') || mimetype.includes('rar') || mimetype.includes('7z') || mimetype.includes('gzip')) return 'zips';
    return 'others';
  }

  getTempDir(fileName) {
    if (!this.fileMap[fileName]) {
      const tempDir = path.join(__dirname, '../resource', `${fileName}-${Date.now()}`)
      fs.mkdirSync(tempDir, { recursive: true });
      this.fileMap[fileName] = tempDir
    }
    return this.fileMap[fileName]
  }

}
